<route lang="jsonc" type="page">
    {
      "style": {
			"navigationStyle": "custom",
			"navigationBarTitleText": "订单结算"
		}
    }
</route>

<script lang="ts" setup>
import checkIcon from '@img/check.png'
import checkedIcon from '@img/checked.png'
import { getUserData } from '@/api/user'
import { useSafeAreaInsets } from '@/mixins/basic'
import HeaderNavbar from '@/pages/components/header-navbar.vue'
import FabServices from '@/pages/components/services.vue'
import { useOrder } from '@/store/order'
import CouponCard from '../components/coupon-card.vue'

defineOptions({
  name: 'Summary',
})

const orderStore = useOrder()

const { safeAreaInsets } = useSafeAreaInsets()
const cardInfo = ref([])
// 次卡勾选的数组
const selectCard = ref([])
const couponRef = ref(null)
const loading = ref(false)

onMounted(() => {
  getCardInfo()
  
  getExtraInfo()
  // 初始化支付按钮加载值
  orderStore.payLoading = false
})

// 获取服务明细数据
const getChildren = computed(() => {
	return orderStore.orderInfo.selectServices.map(item => item.children).flat()
})

// 合计总金额
const summaryMoney = computed(() => {
	const childArr = getChildren.value.filter(fl => !fl.select_card)

	const priceArr = childArr.map((item: AnyObject) => Number(item.price))

	let total = priceArr.reduce((prev: any, curr: any) => {
		// 累加总价
		return prev + curr
	}, 0)
	// 优惠券计算
	if (couponRef.value?.couponArr) {
		const couponPrice = couponRef.value.couponArr.filter(fl => fl.price).map(map => map.price).reduce((prev: any, curr: any) => {
			// 累加总价
			return prev + curr
		}, 0)
		const sumPrice = total - couponPrice
		total = sumPrice < 0 ? 0 : sumPrice
	}
	
	// 运费计算
	total += orderStore.orderInfo.express_fee

	return total.toFixed(2)
})

// 获取用户所有的信息
function getCardInfo() {
  getUserData().then((res) => {
    // to do list ... (暂时将返回的变成数组)
    cardInfo.value = res.userCard
    // cardInfo.value = [
    // 	{
    // 		count: 9,
    // 		settingsCard: {id: 1, name: "修刃次卡", count: 1},
    // 		settings_card_id: 2,
    // 		total: 10
    // 	}
    // ]
  })
}
// 是否显示次卡选项
const getShowCardSelect = computed(() => {
  return (child: AnyObject) => {
    // if (cardInfo.value.length < 0) return {
    // 	count: 0
    // }

    return cardInfo.value.find(fl => fl.settings_card_id === child.settings_card_id) || {
      count: 0,
    }
  }
})

function handleCard(child: AnyObject) {
  const isSelect = !child.select_card
  const index = cardInfo.value.findIndex(fl => fl.settings_card_id === child.settings_card_id)
  const { select_num = 0, count = 0 } = { ...cardInfo.value.find(fl => fl.settings_card_id === child.settings_card_id) }

  if (isSelect) {
    if (select_num >= count) {
      uni.showToast({
        icon: 'none',
        title: '次卡次数不足',
      })
      return
    }

    cardInfo.value[index].select_num = select_num + 1
    // 减去当前选项金额
    // orderStore.setOrderInfo({
    //   totalMoney: Number(orderStore.orderInfo.totalMoney - child.price).toFixed(2),
    // })
  }
  else {
    cardInfo.value[index].select_num = select_num - 1
    // 加上当前选项金额
    // orderStore.setOrderInfo({
    //   totalMoney: Number(Number(orderStore.orderInfo.totalMoney) + Number(child.price)).toFixed(2),
    // })
  }

  child.select_card = isSelect
}

// 获取mode 的支付方式
function getModeType() {
	// 查询是否使用了次卡
	const find = getChildren.value.find(item => item.select_card)
	
	if (summaryMoney.value <= 0) {
	  return 2
	} else if (find) {
	  return 3
	} else {
	  return 1
	}
}
// 获取温度、底刃、边刃的数据
function getExtraInfo() {
	const arr = []
	for (const key in orderStore.extraInfo) {
		arr.push(orderStore.extraInfo[key])
	}
	console.log(arr)
	return arr
}

// 提交订单
function handleConfirm() {
	if (orderStore.payLoading) return

	// 优惠券id
	let voucher_id = []
	// 优惠券码
	let v_photo = []
	// 判断是否选择了优惠券
	if (couponRef.value?.couponArr) {
		for (const item of couponRef.value?.couponArr) {
			if (item.price && !item.code) {
				uni.showToast({
					icon: 'none',
					title: '请输入优惠券码'
				})
				return
			}
			
			voucher_id.push(item.id)
			v_photo.push(item.code)
		}
	}

	// loading.value = true
	orderStore.payLoading = true
	uni.showLoading({
		title: '创建订单中...'
	});

	try {
		// 组装订单数据
		const { selectServices, ...other } = orderStore.orderInfo
		// 服务id
		let service_id_lst = []
		// 服务pid（pid为0的）
		let service_pid_lst = []
		// 使用次卡的服务列表id
		let service_c_id_lst = []
		selectServices.forEach(item => {
			service_pid_lst.push(item.id)
			item.children.forEach(child => {
				service_id_lst.push(child.id)
				
				if (child.select_card) service_c_id_lst.push(child.id)
			})
		})
		
		const mode = getModeType()
		// 订单服务明细
		const extra_info = getExtraInfo().join(';')
		
		let data = {
			eq_id: other.eq_id,
			eq_photo: other.eq_photo,
			// ...other,
			voucher_id: voucher_id.join(','),
			// 优惠券码
			v_photo: v_photo.join(','),
			service_id_lst: service_id_lst.join(','),
			service_pid_lst: service_pid_lst.join(','),
			shop_addr_id: orderStore.selectStore.id,
			kd_type: other.kd_type,
			way: other.way,
			mode,
			service_c_id_lst: service_c_id_lst.join(','),
			express_fee: other.express_fee,
			extra_info
		}
		// 雪具收取
		if (orderStore.orderInfo.kd_type === '2') {
			const address = uni.getStorageSync('addressInfo1')
			data['delivery_addr'] = `联系人：${address.name},联系方式：${address.phone},详细地址：${address.address}`
		}
		
		// 雪具寄送
		if (orderStore.orderInfo.way === '2') {
			const address = uni.getStorageSync('addressInfo2')
			data['pickup_addr'] = `收货人：${address.name},联系方式：${address.phone},详细地址：${address.address}`
		}

		// 创建订单
		orderStore.confirmOrder(data)
	} catch (error) {
		//TODO handle the exception
		console.error('catch---error', error)
		uni.hideLoading()
		orderStore.payLoading = false
	}
}

// 点击返回
function handleBack() {
  // 将选中的次卡变为非选中状态
  orderStore.orderInfo.selectServices.forEach((item) => {
    item.children.forEach((child) => {
      child.select_card = false
    })
  })
}
</script>

<template>
  <view class="summary-page" :style="{ marginTop: `${safeAreaInsets?.top}px` }">
    <header-navbar title="订单结算" @back="handleBack" />

    <view class="card-box">
      <view class="card-title">
        价格明细
      </view>

      <!-- 选中的明细列表 -->
      <view class="details-list">
        <view v-for="item in orderStore.orderInfo.selectServices" :key="item.id" class="details-item">
          <view class="category-name">
            {{ item.name }}
          </view>
          <view v-for="child in item.children" :key="child.id" class="child-item">
            <view class="child-info flex-between">
              <view class="name">
                {{ child.name }}
              </view>
              <view class="price">
                ¥ {{ child.select_card ? '0.00' : child.price }}
              </view>
            </view>

            <!-- 次卡选项 -->
            <view
              v-if="cardInfo.length > 0 && getShowCardSelect(child).count > 0"
              class="check-card"
              @click="handleCard(child)"
            >
              <image class="icon" :class="[{ select: child.select_card }]" :src="child.select_card ? checkedIcon : checkIcon" webp />
              <text class="text">
                使用次卡 (剩余{{ getShowCardSelect(child).count }}次)
              </text>
            </view>
          </view>
        </view>
		<!-- 运费 -->
		<view v-if="orderStore.orderInfo.express_fee > 0" class="details-item">
			<view class="category-name">运费</view>
			
			<view class="child-item">
			  <view class="child-info flex-between">
			    <view class="name">{{ orderStore.orderInfo.express_fee > 50 ? '取送' : '单程' }}</view>
				
				<view class="price">
				  ¥ {{ orderStore.orderInfo.express_fee }}
				</view>
			  </view>
			</view>
		</view>
      </view>
    </view>
    <!-- 优惠券 -->
    <coupon-card ref="couponRef" />

    <view class="fixed-btn" :style="{ paddingBottom: safeAreaInsets?.bottom > 0 ? `${safeAreaInsets?.bottom}px` : null }">
      <!-- 客服按钮 -->
      <FabServices />

      <view class="total-money flex-between">
        <view>总计</view>
        <view>¥ {{ summaryMoney }}</view>
      </view>
      <view class="btn-order" @click="handleConfirm">
        提交订单
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
	.summary-page {
  padding: 68px 25px 200px 25px;
  .details-list {
    padding-top: 13px;
    .details-item {
      .check-card {
      }
    }
  }
  .fixed-btn {
    position: fixed;
    left: 0;
    right: 0;
    :deep(.service-fab) {
      position: absolute;
      top: -45px;
    }
  }
}
</style>
